import { v4 as uuidv4 } from "uuid";

import { Md5 } from "ts-md5";
import { randomBytes } from "node:crypto";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();
export default defineEventHandler(async (event) => {
  const body = await readBody(event); //readBody是全局封装好的获取body的方法

  const salt = randomBytes(16).toString("hex");
  let md5: any = new Md5();
  let newPassword = md5
    .appendStr(body.password + salt)
    .end()
    .toString();
  try {
    const newUser = await prisma.user.create({
      data: {
        id: uuidv4(),
        name: "小明",
        username: body.username,
        password: newPassword,
        salt: salt,
      },
      select: { id: true, name: true }, // 可选：指定返回字段‌:ml-citation{ref="3" data="citationList"}
    });
    if (newUser) {
      return responseJson(0, "注册成功", {});
    } else {
      return responseJson(1, "注册失败", {});
    }
  } catch (e) {
    return responseJson(1, "注册失败,账号已被注册", {});
  }
});
